<?php 

/**
 * sfWidgetFormPropelChoice represents a choice widget for a model.
 *
 * @package    symfony
 * @subpackage widget
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfWidgetFormPropelChoice.class.php 12803 2008-11-09 07:26:18Z fabien $
 */
class sfWidgetFormAddMany  extends sfWidgetFormInput
{
    /**
   * Configures the current widget.
   *
   * Available options:
   *
   *  * url:            The URL to call to get the choices to use (required)
   *  * config:         A JavaScript array that configures the JQuery autocompleter widget
   *  * value_callback: A callback that converts the value before it is displayed
   *
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetForm
   */
    protected function configure($options = array(), $attributes = array())
    {
        $this->addRequiredOption('widget');

        sfContext::getInstance()->getConfiguration()->loadHelpers('Url','I18N');
        
        //parent::configure($options, $attributes);
    }

    /**
   * @param  string $name        The element name
   * @param  string $value       The date displayed in this widget
   * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
   * @param  array  $errors      An array of errors for the field
   *
   * @return string An HTML tag string
   *
   * @see sfWidgetForm
   */
    public function render($name, $value = null, $attributes = array(), $errors = array())
    {
        $name = "{$name}[]";
        
        $widget = $this->getOption('widget');
        $id = $this->generateId($name);
        if(!$value || !is_array($value)){
            $value = $value ? $value : null;

            $value = array($value);
        }
        $html = "";

        foreach ($value as $v){

            $html .= '<li>'.$widget->render($name , $v).'</li>';
        }

        $js = $this->getJavaScript($name , $widget);
        $a_link = "<a href='javascript:;' onclick='{$id}_generate_widget(this)'>".__('Add One')."</a>";
        $separator = "<div style='clear:both'></div>";
        
        return "<div>{$a_link}{$separator}<ul>{$html}</ul></div>{$js}";


    }


    protected function getJavaScript($name , $widget){
        $id = $this->generateId($name);

        return sprintf(<<<EOF
<script type="text/javascript">
function %s_generate_widget(a_obj){
    var str = '%s';
    $(a_obj).parent().children('ul:eq(0)').append('<li>'+str+'</li>');
}
</script>
EOF
        ,$id
        ,str_replace("'","\\'",preg_replace('/\s+/',' ',$widget->render($name)))
        //,$widget->render($name)
        //,str_replace("'","\\'",$widget->render($name))
        );

    }

}